package gatewaylogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/link/gateway/constant"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DelGatewayLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelGatewayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelGatewayLogic {
	return &DelGatewayLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DelGatewayLogic) DelGateway(in *iotpb.DelGatewayReq) (*iotpb.DelGatewayResp, error) {
	// 先判断出每一个网关的状态，如果状态是已开启，则不让删除
	var gatewayList []*model.IotGateway
	for _, v := range in.GetIds() {
		// 查询数据
		one, err := l.svcCtx.IotGatewayModel.FindOne(l.ctx, v)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
				tool.GetErrMsgFormat("delete gateway"), err, in)
		}

		// 判断是否已经启动
		if one.State == constant.GatewayStateOpen {
			gatewayList = append(gatewayList, one)
			continue
		}

		return nil, errors.Wrapf(xerr.NewErrMsg("删除设备网关失败：ID："+
			convertor.ToString(one.Id)+"，名称："+one.Name+"，已启动，请关闭后再删除"),
			tool.GetErrMsgFormat("delete gateway"),
			"gateway id: "+convertor.ToString(one.Id)+", name: "+one.Name+", is opened", in)
	}

	// 删除数据
	err := l.svcCtx.IotGatewayModel.DeleteEx(l.ctx, nil, in.GetIds(), in.GetIsDel(), in.GetUpdateUser())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("delete gateway"), err, in)
	}

	return &iotpb.DelGatewayResp{}, nil
}
